﻿using System;
using System.Text;
using System.Net.Sockets;

namespace AsyncEvtEcho
{
    static class Utility
    {
        public const int CmdToUpper = 101;
        public const int CmdToLower = 102;

        public static string GetCmdDescription(int cmd)
        {
            switch (cmd)
            {
                case CmdToUpper:
                    return "Upper";
                case CmdToLower:
                    return "Lower";
                default:
                    throw new ArgumentOutOfRangeException("non-recognized command");
            }
        }

        public static Tuple<Header, byte[]> MakePacket(this string content, int cmd)
        {
            byte[] buffer = Encoding.ASCII.GetBytes(content);
            Header header = new Header { Command = cmd, Size = buffer.Length };
            return Tuple.Create(header, buffer);
        }

        public static byte[] CombineBinary(this Tuple<Header, byte[]> packet)
        {
            byte[] combined = new byte[Header.BinaryLength + packet.Item2.Length];
            Buffer.BlockCopy(packet.Item1.BinaryImage, 0, combined, 0, Header.BinaryLength);
            Buffer.BlockCopy(packet.Item2, 0, combined, Header.BinaryLength, packet.Item2.Length);
            return combined;
        }

        public static void StartRecvSocket(this HeadBodyRecver recvFSM, Socket socket, SocketAsyncEventArgs evtArgs, Action<SocketAsyncEventArgs> recvCallback)
        {
            Tuple<byte[], int, int> nextRead = recvFSM.NextRead;
            evtArgs.SetBuffer(nextRead.Item1, nextRead.Item2, nextRead.Item3);

            if (!socket.ReceiveAsync(evtArgs))
                recvCallback(evtArgs);
        }
    }
}
